<template>
  <el-dialog :title="!dataForm.skuAttrId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="关联商品ID" prop="productId">
        <ProductAutocomplete v-model.number="dataForm.productId"></ProductAutocomplete>
        <!-- <span>{{ dataForm }}</span> -->
      </el-form-item>
      <el-form-item label="销售属性名（如：颜色）" prop="attrName">
        <el-input v-model="dataForm.attrName" placeholder="销售属性名（如：颜色）"></el-input>
      </el-form-item>
      <el-form-item label="可选值列表" prop="attrValues">
        <el-input v-model="inputValue" @keyup.enter.native="handleInputConfirm" placeholder="输入属性值后按回车"></el-input>
        <div style="margin-top: 10px;">
          <el-tag v-for="(tag, index) in attrValuesToArr" :key="index" closable @close="handleClose(index)"
            style="margin-right: 10px;">
            {{ tag }}
          </el-tag>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>

import ProductAutocomplete from "@/views/modules/common/product-autocomplete"

export default {
  components: {
    ProductAutocomplete
  },
  data() {
    return {
      visible: false,
      inputValue: '',
      dataForm: {
        skuAttrId: 0,
        productId: '',
        attrName: '',
        attrValues: ''
      },
      // Json转换后的可选值列表
      attrValuesToArr: [],
      dataRule: {
        productId: [
          { required: true, message: '关联商品ID不能为空', trigger: 'blur' }
        ],
        attrName: [
          { required: true, message: '销售属性名（如：颜色）不能为空', trigger: 'blur' }
        ],
        attrValues: [
          { required: true, message: '可选值列表不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init(id) {
      this.dataForm.skuAttrId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.skuAttrId) {
          this.$http({
            url: this.$http.adornUrl(`/product/skuattribute/info/${this.dataForm.skuAttrId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.dataForm.productId = data.skuAttribute.productId
              this.dataForm.attrName = data.skuAttribute.attrName
              this.dataForm.attrValues = data.skuAttribute.attrValues
              this.attrValuesToArr = JSON.parse(this.dataForm.attrValues)
            }
          })
        }
      })
    },
    // 处理输入确认
    handleInputConfirm() {
      if (this.inputValue.trim()) {
        this.attrValuesToArr.push(this.inputValue.trim())
        this.dataForm.attrValues = JSON.stringify(this.attrValuesToArr)
      }
      this.inputValue = ''
    },
    // 删除标签
    handleClose(index) {
      this.attrValuesToArr.splice(index, 1)
      this.dataForm.attrValues = JSON.stringify(this.attrValuesToArr)
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/product/skuattribute/${!this.dataForm.skuAttrId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'skuAttrId': this.dataForm.skuAttrId || undefined,
              'productId': this.dataForm.productId,
              'attrName': this.dataForm.attrName,
              'attrValues': this.dataForm.attrValues
            })
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
